package com.plugin.core.util.crypt;

import com.plugin.core.util.MyBase64Util;
import com.plugin.core.util.PropertiesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 */
public class MyAes {

    public static Logger logger = LoggerFactory.getLogger(MyAes.class);
    public static final String ALGORITHM = "AES";
    public static final String CIPHER_ALGORITHM_PKCS5 = "AES/CBC/PKCS5Padding";
    public static final String CIPHER_ALGORITHM_NOPADDING = "AES/CBC/NoPadding";
    // 字符集
    public static final String ENCODING = "UTF-8";
    // 向量
    public static final String IV_SEED = PropertiesUtil.getValueByKey("PUBLIC_AES_SALT");

    public static final String KEY="0123456789ABCDEF";

    /**
     * AES加密算法
     *
     */
    public static String encryptPkcs5Padding(String str) {
        try {
            byte[] raw = KEY.getBytes(ENCODING);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, ALGORITHM);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_PKCS5);
            IvParameterSpec iv = new IvParameterSpec(IV_SEED.getBytes(ENCODING));
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] srawt = str.getBytes(ENCODING);
            int len = srawt.length;
            /* 计算补空格后的长度 */
            while (len % 16 != 0)
                len++;
            byte[] sraw = new byte[len];
            /* 在最后空格 */
            for (int i = 0; i < len; ++i) {
                if (i < srawt.length) {
                    sraw[i] = srawt[i];
                } else {
                    sraw[i] = 32;
                }
            }
            byte[] encrypted = cipher.doFinal(srawt,0,str.length());
            String s=new String(MyBase64Util.encode(encrypted), StandardCharsets.UTF_8);

            return s.replaceAll("\\r", "").replaceAll("\\n", "");
        } catch (Exception ex) {
            logger.error("AES加密出错：" + ex);
            return null;
        }
    }

    /**
     * AES解密算法
     *
     */
    public static String decryptPkcs5Padding(String str) {
        try {
            // 判断Key是否正确
            byte[] raw = KEY.getBytes(ENCODING);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, ALGORITHM);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_PKCS5);
            IvParameterSpec iv = new IvParameterSpec(IV_SEED.getBytes(ENCODING));
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] bytes = MyBase64Util.decode(str.getBytes(ENCODING));
            bytes = cipher.doFinal(bytes);
            return new String(bytes, ENCODING);
        } catch (Exception ex) {
            logger.error("AES解密出错：" + ex);
            return null;
        }
    }


    public static String encryptNoPadding(String Data) {
        try {
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_NOPADDING);
            int blockSize = cipher.getBlockSize();
            byte[] dataBytes = Data.getBytes();
            int plaintextLength = dataBytes.length;
            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }
            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
            SecretKeySpec keyspec = new SecretKeySpec(KEY.getBytes(ENCODING), ALGORITHM);
            IvParameterSpec ivspec = new IvParameterSpec(IV_SEED.getBytes(ENCODING));
            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);
            String EncStr = new String(MyBase64Util.encode(encrypted),ENCODING);//将cipher加密后的byte数组用base64加密生成字符串
            return EncStr ;
        } catch (Exception e) {
            logger.error("exception:",e);
            return null;
        }
    }

    public static String decryptNoPadding(String encryptedData) {
        try {
            byte[] encrypted = MyBase64Util.decode(encryptedData).getBytes(ENCODING);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_NOPADDING);
            SecretKeySpec keyspec = new SecretKeySpec(KEY.getBytes(ENCODING), ALGORITHM);
            IvParameterSpec ivspec = new IvParameterSpec(IV_SEED.getBytes(ENCODING));
            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
            byte[] original = cipher.doFinal(encrypted);
            String originalString = new String(original);
            return originalString.trim();
        } catch (Exception e) {
            logger.error("exception:",e);
            return null;
        }
    }



}
